#!/usr/bin/env bash

# Execute by: bash xxx.sh or bash zzz/yyy/xxx.sh or ./xxx.sh or ./zzz/yyy/xxx.sh source xxx.sh
REALPATH=$(realpath ${BASH_SOURCE[0]})
SCRIPT_DIR=$(cd $(dirname ${REALPATH}) && pwd)
WORK_DIR=$(cd $(dirname ${REALPATH})/.. && pwd)
echo "BASH_SOURCE=${BASH_SOURCE}, REALPATH=${REALPATH}, SCRIPT_DIR=${SCRIPT_DIR}, WORK_DIR=${WORK_DIR}"
cd ${WORK_DIR}

# Get the metadata of machine.
if [[ -f ${WORK_DIR}/containers/data/config/.env ]]; then source ${WORK_DIR}/containers/data/config/.env; fi
echo "LoadEnv CLOUD=$CLOUD REGION=$REGION, SOURCE=$SOURCE"

echo "Try to notify the Redis server to save data"
if [[ ! -z $(pidof redis-server) ]]; then
    REDIS_PARAMS=""
    if [[ ! -z $REDIS_PASSWORD ]]; then REDIS_PARAMS="${REDIS_PARAMS} -a $REDIS_PASSWORD"; fi
    if [[ ! -z $REDIS_PORT ]]; then REDIS_PARAMS="${REDIS_PARAMS} -p $REDIS_PORT"; fi
    RESULT=$(redis-cli $REDIS_PARAMS SAVE) && echo "Redis server saved data: ${RESULT}"
    if [[ $? -ne 0 ]]; then echo "Redis server saved data failed"; exit 1; fi
fi

